import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import prisma from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    
    // 获取用户设置
    const userSettings = await prisma.userSettings.findUnique({
      where: { userId }
    });

    // 如果没有设置记录，创建默认设置
    if (!userSettings) {
      const defaultSettings = await prisma.userSettings.create({
        data: {
          userId,
          theme: 'system',
          themeColor: 'blue',
          language: 'zh_CN',
          emailNotifications: true,
          pushNotifications: true,
          weeklyDigest: true,
        }
      });
      
      return NextResponse.json(defaultSettings);
    }

    return NextResponse.json(userSettings);
  } catch (error) {
    console.error('获取用户设置失败:', error);
    return NextResponse.json(
      { error: '获取用户设置失败' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    const data = await request.json();
    
    // 验证数据
    const validFields = [
      'theme', 
      'themeColor',
      'language', 
      'emailNotifications', 
      'pushNotifications', 
      'weeklyDigest'
    ];
    
    const validData = Object.keys(data)
      .filter(key => validFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);

    // 更新用户设置
    const updatedSettings = await prisma.userSettings.upsert({
      where: { userId },
      update: validData,
      create: {
        userId,
        ...validData,
        // 设置默认值
        theme: validData.theme || 'system',
        themeColor: validData.themeColor || 'blue',
        language: validData.language || 'zh_CN',
        emailNotifications: validData.emailNotifications !== undefined ? validData.emailNotifications : true,
        pushNotifications: validData.pushNotifications !== undefined ? validData.pushNotifications : true,
        weeklyDigest: validData.weeklyDigest !== undefined ? validData.weeklyDigest : true,
      }
    });

    return NextResponse.json(updatedSettings);
  } catch (error) {
    console.error('更新用户设置失败:', error);
    return NextResponse.json(
      { error: '更新用户设置失败' },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    const data = await request.json();
    
    // 验证数据
    const validFields = [
      'theme', 
      'themeColor',
      'language', 
      'emailNotifications', 
      'pushNotifications', 
      'weeklyDigest'
    ];
    
    const validData = Object.keys(data)
      .filter(key => validFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);

    // 更新用户设置
    const updatedSettings = await prisma.userSettings.upsert({
      where: { userId },
      update: validData,
      create: {
        userId,
        ...validData,
        // 设置默认值
        theme: validData.theme || 'system',
        themeColor: validData.themeColor || 'blue',
        language: validData.language || 'zh_CN',
        emailNotifications: validData.emailNotifications !== undefined ? validData.emailNotifications : true,
        pushNotifications: validData.pushNotifications !== undefined ? validData.pushNotifications : true,
        weeklyDigest: validData.weeklyDigest !== undefined ? validData.weeklyDigest : true,
      }
    });

    return NextResponse.json(updatedSettings);
  } catch (error) {
    console.error('更新用户设置失败:', error);
    return NextResponse.json(
      { error: '更新用户设置失败' },
      { status: 500 }
    );
  }
} 